package com.nep.NEPM.controller;

import com.nep.entity.administrator.User;
import com.nep.entity.supervisor.Report;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SupervisorListViewController {
    @FXML
    private Button btn_OUT;
    @FXML
    private ComboBox<String> cmbProvince, cmbCity;
    @FXML
    private DatePicker datePicker;
    @FXML
    private ComboBox<String> cmbEstimatedGrade;
    @FXML
    private ToggleGroup genderGroup;
    @FXML
    private RadioButton rdoAssigned, rdoNoAssigned;
    @FXML
    private TableColumn<User, String> colId;
    @FXML
    private TableColumn<User, String> colName;
    @FXML
    private TableColumn<User, String> colProvince;
    @FXML
    private TableColumn<User, String> colCity;
    @FXML
    private TableColumn<User, String> colGrade;
    @FXML
    private TableColumn<User, String> colDate;
    @FXML
    private TableColumn<User, String> colTime;
    @FXML
    private TableColumn<User, Void> colDetail;
    @FXML
    private TableColumn<User, Void> colAssign;
    @FXML
    private TableView<User> tableView;

    private Map<String, List<String>> provinceMap = new HashMap<>();
    private Map<String, List<String>> estimatedGradeMap = new HashMap<>();

    private ObservableList<User> userList = FXCollections.observableArrayList();

    public void initialize() {
        readReportsFromFile();

        tableView.setItems(userList);
        colId.setCellValueFactory(new PropertyValueFactory<>("id"));
        colName.setCellValueFactory(new PropertyValueFactory<>("name"));
        colProvince.setCellValueFactory(new PropertyValueFactory<>("province"));
        colCity.setCellValueFactory(new PropertyValueFactory<>("city"));
        colGrade.setCellValueFactory(new PropertyValueFactory<>("grade"));
        colDate.setCellValueFactory(new PropertyValueFactory<>("date"));
        colTime.setCellValueFactory(new PropertyValueFactory<>("time"));

        colDetail.setCellFactory(cols -> new TableCell<>() {
            private Button btn = new Button("详情");

            {
                btn.setOnAction(e -> {
                    try {
                        // 获取当前行的用户数据
                        User user = getTableView().getItems().get(getIndex());

                        // 加载SupervisorView界面
                        Stage stage = new Stage();
                        FXMLLoader fxmlLoader = new FXMLLoader();
                        URL url = getClass().getResource("../view/SupervisorView.fxml");
                        fxmlLoader.setLocation(url);
                        Parent root = fxmlLoader.load();

                        // 获取控制器并传递用户数据
                        SupervisorViewController controller = fxmlLoader.getController();
                        controller.initData(user);

                        // 设置场景并显示窗口
                        Scene scene = new Scene(root);
                        stage.setScene(scene);
                        stage.setTitle("公众监督数据详情 - " + user.getName());
                        stage.showAndWait();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                        // 可以添加错误提示对话框
                        Alert alert = new Alert(Alert.AlertType.ERROR);
                        alert.setTitle("错误");
                        alert.setHeaderText("加载详情页面失败");
                        alert.setContentText(ex.getMessage());
                        alert.showAndWait();
                    }
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                setGraphic(empty ? null : btn);
            }
        });

        // 动态添加按钮列
        // 在指派按钮的代码中修改为：
        colAssign.setCellFactory(cols -> new TableCell<>() {
            private Button btn = new Button("指派");

            {
                btn.setOnAction(e -> {
                    try {
                        User user = getTableView().getItems().get(getIndex());
                        FXMLLoader fxmlLoader = new FXMLLoader();
                        URL url = getClass().getResource("../view/SupervisorLocalView.fxml");
                        fxmlLoader.setLocation(url);
                        Parent root = fxmlLoader.load();

                        SupervisorLocalViewController controller = fxmlLoader.getController();
                        controller.initData(user, SupervisorListViewController.this); // 传递当前控制器

                        Stage stage = new Stage();
                        stage.setScene(new Scene(root));
                        stage.setTitle("公众监督数据详情 - " + user.getName());
                        stage.showAndWait();
                    } catch (IOException ex) {
                        // 错误处理
                    }
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                setGraphic(empty ? null : btn);
            }
        });

        // 添加单选按钮的监听器
        genderGroup = new ToggleGroup();// 创建一个单选的选项组
        rdoAssigned.setToggleGroup(genderGroup);// 将单选按钮设置到同一个组中
        rdoNoAssigned.setToggleGroup(genderGroup);
        genderGroup.selectedToggleProperty().addListener((obs, oldToggle, newToggle) -> {
            if (newToggle == null) {
                // 没有选择任何单选按钮，显示所有数据
                tableView.setItems(userList);
            } else {
                RadioButton selectedRadioButton = (RadioButton) newToggle;
                boolean isAssigned = selectedRadioButton == rdoAssigned;

                // 过滤数据
                ObservableList<User> filteredList = userList.stream()
                        .filter(user -> user.isAssigned() == isAssigned)
                        .collect(Collectors.toCollection(FXCollections::observableArrayList));

                tableView.setItems(filteredList);
            }
        });

        // 初始化下拉列表数据
        estimatedGradeMap.put("优", List.of());
        estimatedGradeMap.put("良", List.of());
        estimatedGradeMap.put("轻度污染", List.of());
        estimatedGradeMap.put("中度污染", List.of());
        estimatedGradeMap.put("重度污染", List.of());
        estimatedGradeMap.put("严重", List.of());
        provinceMap.put("安徽省", List.of("合肥", "芜湖", "淮南", "阜阳"));
        provinceMap.put("北京市", List.of("北京"));
        provinceMap.put("重庆市", List.of("重庆"));
        provinceMap.put("福建省", List.of("福州", "厦门", "莆田", "泉州"));
        provinceMap.put("甘肃省", List.of("兰州")); // 注：西宁属青海省，此处按用户原分类调整
        provinceMap.put("广东省", List.of("广州", "深圳", "东莞", "佛山", "惠州", "汕头", "珠海", "江门", "湛江"));
        provinceMap.put("广西壮族自治区", List.of("南宁", "柳州", "桂林"));
        provinceMap.put("贵州省", List.of("贵阳"));
        provinceMap.put("海南省", List.of("海口"));
        provinceMap.put("河北省", List.of("石家庄", "唐山", "廊坊", "大同", "秦皇岛", "张家口", "邢台", "保定"));
        provinceMap.put("河南省", List.of("郑州", "洛阳", "开封", "新乡", "南阳"));
        provinceMap.put("黑龙江省", List.of("哈尔滨", "齐齐哈尔", "大庆"));
        provinceMap.put("湖北省", List.of("武汉", "襄阳", "宜昌"));
        provinceMap.put("湖南省", List.of("长沙", "岳阳", "衡阳", "株洲"));
        provinceMap.put("吉林省", List.of("长春", "吉林", "大庆"));
        provinceMap.put("江苏省", List.of("南京", "苏州", "无锡", "南通", "徐州", "盐城", "扬州", "常州"));
        provinceMap.put("江西省", List.of("南昌", "赣州", "上饶"));
        provinceMap.put("辽宁省", List.of("沈阳", "大连", "鞍山", "抚顺", "锦州", "营口"));
        provinceMap.put("内蒙古自治区", List.of("呼和浩特", "包头", "赤峰"));
        provinceMap.put("宁夏回族自治区", List.of("银川"));
        provinceMap.put("山东省", List.of("济南", "青岛", "淄博", "烟台", "临沂", "济宁", "泰安", "潍坊"));
        provinceMap.put("山西省", List.of("太原", "大同", "长治"));
        provinceMap.put("陕西省", List.of("西安", "咸阳"));
        provinceMap.put("上海市", List.of("上海"));
        provinceMap.put("四川省", List.of("成都", "绵阳", "泸州", "宜宾", "南充"));
        provinceMap.put("天津市", List.of("天津"));
        provinceMap.put("新疆维吾尔自治区", List.of("乌鲁木齐"));
        provinceMap.put("西藏自治区", List.of("拉萨"));
        provinceMap.put("云南省", List.of("昆明"));
        provinceMap.put("浙江省", List.of("杭州", "宁波", "温州", "绍兴", "台州", "义乌", "慈溪"));
        provinceMap.put("青海省", List.of("西宁"));
        cmbEstimatedGrade.setItems(FXCollections.observableArrayList(estimatedGradeMap.keySet()));
        cmbEstimatedGrade.getSelectionModel().clearSelection();
        cmbProvince.setItems(FXCollections.observableArrayList(provinceMap.keySet()));
        cmbProvince.getSelectionModel().clearSelection();
        cmbProvince.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) {
                List<String> citys = provinceMap.getOrDefault(newValue, List.of());
                cmbCity.setItems(FXCollections.observableArrayList(citys));
                cmbCity.getSelectionModel().clearSelection();
            }
        });
        datePicker.setValue(LocalDate.now());
        // 添加监听时间，处理选择的时间
        datePicker.valueProperty().addListener(new ChangeListener<LocalDate>() {
            @Override
            public void changed(ObservableValue<? extends LocalDate> observableValue, LocalDate oldDate, LocalDate newDate) {
                System.out.println("选择的日期为：" + newDate);
            }
        });
    }

    private void readReportsFromFile() {
        try (BufferedReader reader = new BufferedReader(new FileReader("reports.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                Report report = Report.deserialize(line);
                if (report == null) {
                    continue; // 跳过无效行
                }
                String userId = report.getUserId();
                String userName = report.getUserName();
                String aqiLevel = report.getAqiLevel();
                String gridAddr = report.getGridAddr();
                String reportId = report.getReportId();
                String description = report.getDescription();

                String province = "";
                String city = "";
                String[] addrParts = gridAddr.split(" ");
                if (addrParts.length > 0) {
                    province = addrParts[0];
                }
                if (addrParts.length > 1) {
                    city = addrParts[1];
                }

                User user = new User();
                user.setId(userId);
                user.setName(userName);
                user.setGrade(aqiLevel);
                user.setProvince(province);
                user.setCity(city);
                user.setDate(report.getCreateTime().toLocalDate().toString());
                user.setTime(report.getCreateTime().toLocalTime().toString());
                user.setAssigned(false);

                userList.add(user);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @FXML
    private void clearFilters() {
        cmbProvince.getSelectionModel().clearSelection();
        cmbCity.getSelectionModel().clearSelection();
        cmbEstimatedGrade.getSelectionModel().clearSelection();
        datePicker.setValue(null);
        genderGroup.selectToggle(null);

        // 重置表格显示所有数据
        tableView.setItems(userList);
    }

    // 查询方法
    @FXML
    private void search() {
        String selectedProvince = cmbProvince.getValue();
        String selectedCity = cmbCity.getValue();
        String selectedGrade = cmbEstimatedGrade.getValue();
        LocalDate selectedDate = datePicker.getValue();
        RadioButton selectedRadio = (RadioButton) genderGroup.getSelectedToggle();
        Boolean isAssigned = selectedRadio != null ? (selectedRadio == rdoAssigned) : null;

        // 过滤数据
        ObservableList<User> filteredList = userList.stream()
                .filter(user -> selectedProvince == null || user.getProvince().equals(selectedProvince))
                .filter(user -> selectedCity == null || user.getCity().equals(selectedCity))
                .filter(user -> selectedGrade == null || user.getGrade().equals(selectedGrade))
                .filter(user -> selectedDate == null || user.getDate().equals(selectedDate.toString()))
                .filter(user -> isAssigned == null || user.isAssigned() == isAssigned)
                .collect(Collectors.toCollection(FXCollections::observableArrayList));

        // 更新表格数据
        tableView.setItems(filteredList);
    }

    public void updateUserAssignmentStatus(String userId, boolean isAssigned) {
        for (User user : userList) {
            if (user.getId().equals(userId)) {
                user.setAssigned(isAssigned);
                break;
            }
        }
        tableView.refresh(); // 刷新表格显示
    }

    public void OUT(ActionEvent actionEvent) throws IOException {
        Stage stage = (Stage) btn_OUT.getScene().getWindow();
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("../view/IndexView.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = btn_OUT.getScene();
        scene.setRoot(root);
        stage.setScene(scene);
        stage.show();
    }
}
